package controller;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import domain.Address;
import domain.Contact;
import domain.ContactGroup;
import domain.factory.POJOFactory;
import domain.itf.IDAOContact;

/**
 * Controller class tester of the cache
 */
@Controller
@RequestMapping("/TestCache")
public class TestCacheController {

	@Autowired
    ServletContext servletContext;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");
		
		ApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		try
		{
			Address address;
			Contact contact;
			ContactGroup contactGroup = POJOFactory.instance.newContactGroup("group test cache", null);
			Set<ContactGroup> books = new HashSet<ContactGroup>();
			books.add(contactGroup);
			IDAOContact daoContact = (IDAOContact) context.getBean("DAOContact");
			for (int i = 0; i < 100; i++) {
				address = POJOFactory.instance.newAddress(i + " rue Chales Royet", "Riom", "63200", "France");
				contact = POJOFactory.instance.newContact("Contact" + String.valueOf(i), "ContactName" + String.valueOf(i), "con.tact"+String.valueOf(i)+"@gmail.com", address, books, null);
				daoContact.addContact(contact);
			}
			
			for (int i = 0; i < 40; i++) {
				daoContact.getAllContacts();
			}
			
			view.addObject("messageInfo","The cache test is done.");
		}
		catch(Exception e)
		{
			view.addObject("messageError","The cache test has failed.");
		}
		return view;
	}
	

}
